import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod_demo/models/userinfo.dart';
import 'package:sp_util/sp_util.dart';

import '../providers/policy.dart';

class LoginPage extends ConsumerStatefulWidget {
  const LoginPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _LoginPageState();
}

class _LoginPageState extends ConsumerState<LoginPage> {
  final _accountController = TextEditingController(text: "admin");
  final _passwordController = TextEditingController(text: "admin78651243");
  final _captchaController = TextEditingController();

  late Map<String, dynamic> captchaData;

  @override
  Widget build(BuildContext context) {
    var captcha = ref.watch(captchaProvider);
    var screenWidth = MediaQuery.of(context).size.width;
    var screenHeight = MediaQuery.of(context).size.height;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Login'),
        centerTitle: true,
      ),
      body: Container(
        margin: EdgeInsets.only(left: 30, right: 30, top: screenHeight * 0.2),
        child: Column(
          children: [
            TextField(
              controller: _accountController,
              decoration: const InputDecoration(
                hintText: '用户名',
              ),
            ),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                hintText: '密码',
              ),
            ),
            Row(
              children: [
                captcha.when(
                  data: (value) {
                    captchaData = value.data as Map<String, dynamic>;
                    var captchaImage = captchaData["image"] as String;
                    debugPrint(captchaImage);
                    return GestureDetector(
                      onTap: () {
                        ref.refresh(captchaProvider);
                        // debugPrint(refresh.value.toString());
                      },
                      child: Image(
                          width: 120,
                          height: 60,
                          image: MemoryImage(
                            const Base64Decoder().convert(captchaImage
                                .replaceFirst("data:image/png;base64,", "")),
                          )),
                    );
                  },
                  error: (error, stack) => Text('Error: ${error.toString()}'),
                  loading: () => const CircularProgressIndicator(),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: TextField(
                    controller: _captchaController,
                    decoration: const InputDecoration(
                      hintText: '验证码',
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              style: ButtonStyle(
                  fixedSize:
                      MaterialStateProperty.all(Size(screenWidth - 60, 40))),
              onPressed: () async {
                if (_accountController.text.isEmpty) {
                  BotToast.showText(text: "用户名不能为空");
                  return;
                }
                if (_passwordController.text.isEmpty) {
                  BotToast.showText(text: "密码不能为空");
                  return;
                }
                if (_captchaController.text.isEmpty) {
                  BotToast.showText(text: "验证码不能为空");
                  return;
                }
                // 跳转页面
                Map<String, dynamic> requestBody = {
                  "grantType": "captcha",
                  "tenantId": "000000",
                  "type": "account",
                  "account": _accountController.text,
                  "password": _passwordController.text,
                };
                Map<String, dynamic> requestHeader = {
                  "Captcha-Key": captchaData["key"] as String,
                  "Captcha-Code": _captchaController.text
                };
                var loginResuslt = await ref
                    .read(loginProvider(requestBody, requestHeader).future);
                debugPrint(loginResuslt.toString());
                if (loginResuslt.code != 200) {
                  BotToast.showText(text: loginResuslt.msg);
                  return;
                }
                var userInfo = UserInfo.fromJson(loginResuslt.data);
                SpUtil.putString("accessToken", userInfo.accessToken as String);
                SpUtil.putObject("userInfo", userInfo);
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  Navigator.of(context).pushReplacementNamed("/home");
                });
              },
              child: const Text('登录'),
            )
          ],
        ),
      ),
    );
  }
}
